#! /bin/bash

kubepath=$1
crdpath=$2

exit_fun () {
    echo 'Error: exited...'
    exit 1
}

if [ -z $kubepath  ]; then
    echo 'Usage: switchcrd.sh KUBECONFIG_PATH CRD_PATH.'
    echo 'arg1 is cluster kubeconfig path, arg2 is the path where CRD is replaced'
    exit_fun
elif [ -z $crdpath ]; then
    echo 'Error: Missing CRD path.'
    exit_fun
elif [ ! -f $kubepath ]; then
    echo 'Error: Kubeconfig file not existed.'
    exit_fun
elif [ ! -d $crdpath ]; then
    echo 'Error: CRD directory not existed.'
    exit_fun
fi

check_crd() {
    grep "kind: CustomResourceDefinition" $crdpath/$crd > /dev/null
    if [ $? != 0 ]; then
        echo "Error: $crdpath/$crd CRD file is not a CustomResourceDefinition kind."
        exit_fun
    fi
}

replace() {
    for crd in $(ls $crdpath); do
        check_crd
        kubectl replace -f $crdpath/$crd --kubeconfig $kubepath
    done
}

replace